package com.easemob.chat;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build.VERSION;
import android.os.Process;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.easemob.EMCallBack;
import com.easemob.analytics.EMLoginCollector;
import com.easemob.analytics.EMTimeTag;
import com.easemob.b.a;
import com.easemob.chat.core.HeartBeatReceiver;
import com.easemob.chat.core.XmppConnectionManager;
import com.easemob.chat.core.k;
import com.easemob.cloud.HttpClientConfig;
import com.easemob.cloud.HttpClientManager;
import com.easemob.exceptions.EMAuthenticationException;
import com.easemob.exceptions.EMNetworkUnconnectedException;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.CryptoUtils;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;
import com.easemob.util.PathUtil;
import java.io.IOException;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.http.conn.ConnectTimeoutException;
import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.XMPPConnection;
import org.json.JSONException;
import org.json.JSONObject;

class EMSessionManager
{
  private static final String TAG = "Session";
  private XmppConnectionManager xmppConnectionManager = null;
  private Context appContext = null;
  private static final String PREF_KEY_LOGIN_USER = "easemob.chat.loginuser";
  private static final String PREF_KEY_LOGIN_PWD = "easemob.chat.loginpwd";
  public EMContact currentUser = null;
  private static EMSessionManager instance = new EMSessionManager();
  private String lastLoginUser = null;
  private String lastLoginPwd = null;
  private HeartBeatReceiver heartbeatReceiver = null;
  private PendingIntent heartbeatIntent = null;
  private static final int HEARTBEAT_INTERVAL = 180;
  private static final int WIFI_HEARTBEAT_INTERVAL = 120;
  private boolean loginOngoing = false;
  private Object loginLock = new Object();

  public static synchronized EMSessionManager getInstance(Context paramContext)
  {
    if (paramContext != null)
      instance.appContext = paramContext;
    return instance;
  }

  public static synchronized EMSessionManager getInstance()
  {
    if (instance.appContext == null)
      instance.appContext = EMChat.getInstance().getAppContext();
    return instance;
  }

  synchronized EMSessionManager onInit()
  {
    if (this.appContext == null)
      this.appContext = EMChat.getInstance().getAppContext();
    return this;
  }

  private void initXmppConnection(String paramString1, String paramString2)
  {
    if (this.xmppConnectionManager != null)
      try
      {
        EMLog.d("Session", "try to disconnect previous connection");
        this.xmppConnectionManager.disconnect();
      }
      catch (Exception localException)
      {
        localException.printStackTrace();
      }
    else
      this.xmppConnectionManager = new XmppConnectionManager();
    this.xmppConnectionManager.onInit(paramString1, paramString2);
    EMChatManager.getInstance().onNewConnectionCreated(this.xmppConnectionManager);
  }

  void checkConnection()
    throws EaseMobException
  {
    EMLog.d("Session", "check connection...");
    if (this.xmppConnectionManager == null)
      throw new EMNetworkUnconnectedException("xmppConnectionManager is null");
    if (this.xmppConnectionManager.getConnection() == null)
      throw new EMNetworkUnconnectedException("connection is null");
    if ((!this.xmppConnectionManager.isConnected()) || (!this.xmppConnectionManager.getConnection().isAuthenticated()))
    {
      EMLog.e("Session", "network unconnected");
      throw new EMNetworkUnconnectedException("connection is not connected");
    }
    EMLog.d("Session", "check connection ok");
  }

  void loadDB()
  {
    EMChatManager.getInstance().loadDB();
  }

  private synchronized void loginSync(String paramString1, String paramString2, boolean paramBoolean, EMCallBack paramEMCallBack)
  {
    if ((paramString1 == null) || (paramString2 == null) || (paramString1.equals("")) || (paramString2.equals("")))
    {
      if (paramEMCallBack != null)
        paramEMCallBack.onError(-1005, "the username or password is null or empty!");
      return;
    }
    String str1 = getLastLoginUser();
    String str2 = getLastLoginPwd();
    int i = 0;
    if ((str1 != null) && (str2 != null))
      i = (str1.equals(paramString1)) && (str2.equals(paramString2)) ? 1 : 0;
    EMLog.d("Session", "loginSync : in process " + Process.myPid());
    String str3 = EMContactManager.getBareEidFromUserName(paramString1);
    EMLog.d("Session", "login with eid:" + str3);
    EMTimeTag localEMTimeTag = new EMTimeTag();
    localEMTimeTag.start();
    if ((isConnected()) && (i != 0))
    {
      this.loginOngoing = false;
      EMLog.d("Session", "resue existing connection manager");
      this.xmppConnectionManager.reuse();
      EMLog.d("Session", "already loggedin and conected. skip login");
      if (paramEMCallBack != null)
        paramEMCallBack.onSuccess();
      return;
    }
    if (EMChatConfig.isDebugTrafficMode())
      a.a();
    this.currentUser = new EMContact(str3, paramString1);
    try
    {
      loadDB();
    }
    catch (Exception localException1)
    {
      this.loginOngoing = false;
      localException1.printStackTrace();
      if (paramEMCallBack != null)
        paramEMCallBack.onError(-1, localException1.toString());
    }
    try
    {
      k.a().a(paramString1, paramString2);
    }
    catch (JSONException localJSONException)
    {
      this.loginOngoing = false;
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1000, "Wrong response result was returned from server : " + localJSONException.getMessage());
        return;
      }
    }
    catch (UnknownHostException localUnknownHostException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "unknow host exception:" + localUnknownHostException.toString());
      if ((paramBoolean) && (!NetUtils.hasNetwork(this.appContext)))
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1001, "there is not network connction, please check you network");
        return;
      }
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1002, "can't resolve DNS host");
        return;
      }
    }
    catch (NoRouteToHostException localNoRouteToHostException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "NoRouteToHostException:" + localNoRouteToHostException.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1003, "can not connect to server : " + localNoRouteToHostException.toString());
        return;
      }
    }
    catch (ConnectException localConnectException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "ConnectException:" + localConnectException.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1003, "can not connect to server : " + localConnectException.toString());
        return;
      }
    }
    catch (SocketException localSocketException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "SocketException:" + localSocketException.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1003, "can not connect to server : " + localSocketException.toString());
        return;
      }
    }
    catch (SocketTimeoutException localSocketTimeoutException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "SocketTimeoutException:" + localSocketTimeoutException.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1004, "server response timer out");
        return;
      }
    }
    catch (EMAuthenticationException localEMAuthenticationException1)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "EMAuthenticationException:" + localEMAuthenticationException1.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1005, "invalid user or password");
        return;
      }
    }
    catch (ConnectTimeoutException localConnectTimeoutException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "ConnectTimeoutException:" + localConnectTimeoutException.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1004, "connection timer out");
        return;
      }
    }
    catch (IOException localIOException)
    {
      this.loginOngoing = false;
      EMLog.e("Session", "IOException:" + localIOException.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1007, "IO exception : " + localIOException.toString());
        return;
      }
    }
    catch (Exception localException2)
    {
      this.loginOngoing = false;
      if (localException2 != null)
        EMLog.e("Session", "Exception:" + localException2.toString());
      if (paramBoolean)
      {
        if (paramEMCallBack != null)
          paramEMCallBack.onError(-1003, "failed to connect to server ：" + localException2.toString());
        return;
      }
    }
    try
    {
      this.appContext = EMChat.getInstance().getAppContext();
      initXmppConnection(str3, paramString2);
      PathUtil.getInstance().initDirs(EMChatConfig.getInstance().APPKEY, paramString1, this.appContext);
      this.xmppConnectionManager.setChatTag(localEMTimeTag);
      this.xmppConnectionManager.connectSync(paramBoolean);
      scheduleNextHeartBeat();
      String str4 = getLastLoginUser();
      if (!paramString1.equals(str4))
      {
        setLastLoginUser(paramString1);
        setLastLoginPwd(paramString2);
      }
      EMContactManager.getInstance().init(this.appContext, this.xmppConnectionManager);
    }
    catch (EMAuthenticationException localEMAuthenticationException2)
    {
      localEMAuthenticationException2.printStackTrace();
      this.loginOngoing = false;
      if (paramEMCallBack != null)
      {
        EMLog.e("Session", "EMAuthenticationException failed: " + localEMAuthenticationException2.toString());
        paramEMCallBack.onError(-1005, "invalid password or username");
      }
      return;
    }
    catch (Exception localException3)
    {
      this.loginOngoing = false;
      if (localException3 != null)
      {
        localException3.printStackTrace();
        EMLog.e("Session", "xmppConnectionManager.connectSync() failed: " + localException3.getMessage());
      }
      if (paramEMCallBack != null)
        paramEMCallBack.onError(-1003, localException3.getMessage());
      return;
    }
    this.loginOngoing = false;
    EMLog.i("Session", "EaseMob Server connected.");
    EMLoginCollector.collectLoginTime(localEMTimeTag.stop());
    if (paramEMCallBack != null)
      paramEMCallBack.onSuccess();
  }

  void login(final String paramString1, final String paramString2, final boolean paramBoolean, final EMCallBack paramEMCallBack)
  {
    EMChatManager.getInstance().initDB(paramString1);
    Thread local1 = new Thread()
    {
      public void run()
      {
        EMSessionManager.this.loginSync(paramString1, paramString2, paramBoolean, paramEMCallBack);
      }
    };
    local1.setPriority(9);
    local1.start();
  }

  public void logout()
  {
    Thread local2 = new Thread()
    {
      public void run()
      {
        EMLog.d("Session", "Session logout");
        EMSessionManager.this.syncLogout();
      }
    };
    local2.setPriority(9);
    local2.start();
  }

  public void syncLogout()
  {
    EMLog.d("Session", "Session logout");
    stopHeartbeatTimer();
    try
    {
      this.xmppConnectionManager.disconnect();
      if (k.a().t())
        k.a().s();
    }
    catch (Exception localException)
    {
    }
    this.loginOngoing = false;
  }

  void scheduleNextHeartBeat()
  {
    try
    {
      AlarmManager localAlarmManager = (AlarmManager)this.appContext.getSystemService("alarm");
      Object localObject;
      if (this.heartbeatIntent == null)
      {
        localObject = new Intent("easemob.chat.heatbeat." + EMChatConfig.getInstance().APPKEY);
        this.heartbeatIntent = PendingIntent.getBroadcast(this.appContext, 0, (Intent)localObject, 0);
      }
      if (this.heartbeatReceiver == null)
      {
        this.heartbeatReceiver = new HeartBeatReceiver(this.xmppConnectionManager);
        localObject = new IntentFilter("easemob.chat.heatbeat." + EMChatConfig.getInstance().APPKEY);
        this.appContext.registerReceiver(this.heartbeatReceiver, (IntentFilter)localObject);
      }
      int i;
      if (NetUtils.isWifiConnection(this.appContext))
        i = 120;
      else
        i = 180;
      Long localLong = Long.valueOf(System.currentTimeMillis() + i * 1000);
      if (Build.VERSION.SDK_INT >= 19)
        localAlarmManager.setExact(0, localLong.longValue(), this.heartbeatIntent);
      else
        localAlarmManager.set(0, localLong.longValue(), this.heartbeatIntent);
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  void stopHeartbeatTimer()
  {
    EMLog.d("Session", "stop heart beat timer");
    try
    {
      AlarmManager localAlarmManager = (AlarmManager)this.appContext.getSystemService("alarm");
      localAlarmManager.cancel(this.heartbeatIntent);
      this.appContext.unregisterReceiver(this.heartbeatReceiver);
      this.heartbeatReceiver = null;
    }
    catch (Exception localException)
    {
      if (!localException.getMessage().contains("Receiver not registered"))
        localException.printStackTrace();
    }
  }

  String getLastLoginUser()
  {
    if (this.lastLoginUser == null)
    {
      SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.appContext);
      this.lastLoginUser = localSharedPreferences.getString("easemob.chat.loginuser", "");
    }
    return this.lastLoginUser;
  }

  void setLastLoginUser(String paramString)
  {
    if (paramString == null)
      return;
    this.lastLoginUser = paramString;
    SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.appContext);
    SharedPreferences.Editor localEditor = localSharedPreferences.edit();
    localEditor.putString("easemob.chat.loginuser", paramString);
    localEditor.commit();
  }

  String getLastLoginPwd()
  {
    if (this.lastLoginPwd == null)
    {
      SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.appContext);
      String str = localSharedPreferences.getString("easemob.chat.loginpwd", "");
      if (str.equals(""))
      {
        this.lastLoginPwd = "";
        return this.lastLoginPwd;
      }
      try
      {
        CryptoUtils localCryptoUtils = EMChatManager.getInstance().getCryptoUtils();
        this.lastLoginPwd = localCryptoUtils.decryptBase64String(str);
      }
      catch (Exception localException)
      {
        localException.printStackTrace();
      }
    }
    return this.lastLoginPwd;
  }

  void clearLastLoginUser()
  {
    try
    {
      this.lastLoginUser = "";
      SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.appContext);
      SharedPreferences.Editor localEditor = localSharedPreferences.edit();
      localEditor.putString("easemob.chat.loginuser", this.lastLoginUser);
      localEditor.commit();
    }
    catch (Exception localException)
    {
    }
  }

  void clearLastLoginPwd()
  {
    try
    {
      this.lastLoginPwd = "";
      SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.appContext);
      SharedPreferences.Editor localEditor = localSharedPreferences.edit();
      localEditor.putString("easemob.chat.loginpwd", this.lastLoginPwd);
      localEditor.commit();
    }
    catch (Exception localException)
    {
    }
  }

  void setLastLoginPwd(String paramString)
  {
    if (paramString == null)
      return;
    this.lastLoginPwd = paramString;
    SharedPreferences localSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.appContext);
    SharedPreferences.Editor localEditor = localSharedPreferences.edit();
    try
    {
      CryptoUtils localCryptoUtils = EMChatManager.getInstance().getCryptoUtils();
      String str = localCryptoUtils.encryptBase64String(paramString);
      localEditor.putString("easemob.chat.loginpwd", str);
      localEditor.commit();
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  public boolean isConnected()
  {
    if (this.xmppConnectionManager == null)
      return false;
    return this.xmppConnectionManager.isConnected() & this.xmppConnectionManager.isAuthentificated();
  }

  XMPPConnection getConnection()
  {
    return this.xmppConnectionManager != null ? this.xmppConnectionManager.getConnection() : null;
  }

  public String getLoginUserName()
  {
    return this.currentUser.username;
  }

  void changePasswordXMPP(String paramString)
    throws EaseMobException
  {
    if ((this.xmppConnectionManager != null) && (this.xmppConnectionManager.isConnected()) && (this.xmppConnectionManager.isAuthentificated()))
    {
      AccountManager localAccountManager = this.xmppConnectionManager.getConnection().getAccountManager();
      try
      {
        localAccountManager.changePassword(paramString);
      }
      catch (Exception localException)
      {
        EMLog.e("Session", "changePasswordInBackground XMPP failed: usr:" + getLoginUserName() + ", newPassword:" + paramString + ", " + localException.toString());
        throw new EaseMobException(localException.getMessage());
      }
    }
    else
    {
      EMLog.e("Session", "changePasswordInBackground failed. xmppConnectionManager is null. ");
      throw new EMNetworkUnconnectedException();
    }
  }

  public void createAccountXMPP(String paramString1, String paramString2)
    throws EaseMobException
  {
    try
    {
      if (this.xmppConnectionManager != null)
        this.xmppConnectionManager.disconnect();
      else
        this.xmppConnectionManager = new XmppConnectionManager();
      this.xmppConnectionManager.onInit();
      this.xmppConnectionManager.connect();
      AccountManager localAccountManager = this.xmppConnectionManager.getConnection().getAccountManager();
      localAccountManager.createAccount(paramString1, paramString2);
      this.xmppConnectionManager.disconnect();
      EMLog.d("Session", "created xmpp user:" + paramString1);
    }
    catch (Exception localException)
    {
      if (this.xmppConnectionManager != null)
        this.xmppConnectionManager.disconnect();
      localException.printStackTrace();
      throw new EaseMobException(localException.toString());
    }
  }

  void forceReconnect()
  {
    if (this.xmppConnectionManager != null)
      this.xmppConnectionManager.forceReconnect();
  }

  public void createAccountRest(String paramString1, String paramString2)
    throws EaseMobException
  {
    if (TextUtils.isEmpty(paramString1))
      throw new EaseMobException("username is empty");
    if (TextUtils.isEmpty(paramString2))
      throw new EaseMobException("password is empty");
    if (TextUtils.isEmpty(EMChatConfig.getInstance().APPKEY))
      throw new EaseMobException("appkey is not set");
    String str1 = null;
    Object localObject;
    try
    {
      String str2 = HttpClientConfig.getBaseUrlByAppKey() + "/users/";
      localObject = new JSONObject();
      ((JSONObject)localObject).put("username", paramString1);
      ((JSONObject)localObject).put("password", paramString2);
      str1 = HttpClientManager.sendHttpRequest(str2, null, ((JSONObject)localObject).toString(), HttpClientManager.Method_POST);
    }
    catch (JSONException localJSONException1)
    {
      throw new EaseMobException(-1000, localJSONException1.getMessage());
    }
    catch (Exception localException)
    {
      if ((localException instanceof EaseMobException))
        throw new EaseMobException(((EaseMobException)localException).getErrorCode(), localException.getMessage());
      throw new EaseMobException(-998, localException.getMessage());
    }
    if (TextUtils.isEmpty(str1))
      throw new EaseMobException(-1007, "response result is null");
    if (str1.contains("error"))
    {
      String str3 = "";
      localObject = "";
      try
      {
        JSONObject localJSONObject = new JSONObject(str1);
        str3 = localJSONObject.getString("error");
        localObject = localJSONObject.getString("error_description");
      }
      catch (JSONException localJSONException2)
      {
        localJSONException2.printStackTrace();
        throw new EaseMobException(-1000, localJSONException2.getMessage());
      }
      if (str3.equalsIgnoreCase("duplicate_unique_property_exists"))
        throw new EaseMobException(-1015, "conflict");
      if (str3.equalsIgnoreCase("unauthorized"))
        throw new EaseMobException(-1021, "unauthorized:" + (String)localObject);
      throw new EaseMobException(-999, (String)localObject);
    }
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     com.easemob.chat.EMSessionManager
 * JD-Core Version:    0.6.1
 */